//
//  InputLayer.m
//  ScrollingWithJoy
//
//  Created by Steffen Itterheim on 12.08.10.
//  Copyright 2010 Steffen Itterheim. All rights reserved.
//

#import "InputLayer.h"
#import "GameScene.h"

#import "RandomNumber.h"
#import "GameOverScene.h"

#import "CCLabel.h"

#import "MenuTest.h"

#import "GameCenterLayer.h"



#define DELTA_STEP   (2)
#define DELTA_BASE   (5)
#define DELTA_DROP_BASE   (-2)
#define DELTA_DROP_STEP   (-2)

@interface InputLayer (PrivateMethods)
-(void) addFireButton;
-(void) addJoystick;
@end

@implementation InputLayer

@synthesize bPowerPressed;
@synthesize posDelta;

@synthesize mFilghtScore;

-(id) init
{
	if ((self = [super init]))
	{
		//[self addFireButton];
		//[self addJoystick];
		
		self.isTouchEnabled=true;
		
		[self myInit];
		

	}
	
	return self;
}


-(void)myInit
{
	
	[self addBg];
	
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
	bPowerPressed=FALSE;
	
	[self initBatch];
	
	
	[self addPause];
	
	_targets=[[NSMutableArray alloc] init];
	
	[self scheduleUpdateWithPriority:2];
	//[self schedule:@selector(update:) interval:0.05];
	
	//[self schedule:@selector(update:) interval:0.1];
	[self schedule:@selector(update2:) interval:0.1];
	
	// Call game logic about every second
	ccTime tmp=[self getInterval];
	[self schedule:@selector(gameLogic:) interval:tmp];
	
	[self schedule:@selector(update_check:)];
	
    
    int fontSize=20;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        fontSize=50;
    }
    else{
        fontSize=20;
    }
    
	mFilghtScore=[CCLabel labelWithString:@"0" 
                                                   fontName:@"Marker Felt"
                                                   fontSize:fontSize];
    mFilghtScore.color=ccc3(0,255,0);
	int w=mFilghtScore.contentSize.width;
	int h=mFilghtScore.contentSize.height;
    
	mFilghtScore.position=ccp(winSize.width-w*6
							  ,winSize.height-h/2);
	
	[self addChild:mFilghtScore];
    
    
    //[self addOpenFeintButton];
    
    
    //[self addSWButton];
}







-(void) dealloc
{
	[_targets release];
	_targets=nil;
	
	[super dealloc];
}

-(void)addBg
{
	
}



-(float)getInterval
{
	float time=1.0;
	
	int level=[GameMusicSetting getGameLevelSeeting];
	switch (level) {
		case NORMAL:
			//time=[self createRandomsizeValueFloat:1.0 toFloat:1.2];   ////range 1.0-2.0
			time=1.5;
			break;
			
		case HARD:
			//time=(float)[self createRandomsizeValueFloat:0.8 toFloat:1.0]; ;   ////range 0.7-1.7
			time=1.2;
			break;
			
			
		case EASY:   ////range 1.5-2.5
			//time=(float)[self createRandomsizeValueFloat:1.2 toFloat:1.5];
			time=2.0;
			break;
			
		default:
			break;
	}
	
	CCLOG(@"getInterval=%f\n",time);
	
	return time;
}



//////////////碰撞检测
-(void)update_check:(ccTime)dt
{
	GameScene* game = [GameScene sharedGameScene];
	ShipEntity* ship = [game defaultShip];	//小鸟
	
	CGRect birdRect = 
	CGRectMake(
			   ship.position.x-(ship.contentSize.width/4)
			   , ship.position.y-(ship.contentSize.height/4)
			   , ship.contentSize.width/4*2
			   , ship.contentSize.height/2);
	
	CCSprite * spike=nil;	
	//CCARRAY_FOREACH([batch children], spike)
	for (spike in _targets) 
	{
		//if (spike.visible)
		{
			////检测小鸟与钉子的碰撞
			
			CGRect spikeRect;
			
			if (SPIKE_TAG_TOP == spike.tag) {
				//top
				//target.anchorPoint=ccp(0.0,1.0);
				spikeRect= 
				CGRectMake(
						   spike.position.x+5
						   , spike.position.y-(spike.contentSize.height*spike.scaleY)
						   , spike.contentSize.width
						   , spike.contentSize.height*spike.scaleY);
				
			}else if (SPIKE_TAG_BOTTOM == spike.tag) {
				//bottom,
				//target.anchorPoint=ccp(0.0,0.0);
				spikeRect= 
				CGRectMake(
						   spike.position.x+5
						   , spike.position.y
						   , spike.contentSize.width
						   , spike.contentSize.height*spike.scaleY);
			}
			
			
			/////检测当前钉子和小鸟的碰撞
			if (CGRectIntersectsRect(birdRect, spikeRect)) 
			{
				//发生了碰撞
				//game over
				[self gameOver];
				
				break;
			}
			
			
		}
	}
	

	
	

}


-(void)gameOver
{
    [self submitGameCenter];
    
    
	GameOverScene * gameOverScene=[GameOverScene node];
	int score=mScore;
	[gameOverScene.layer setScore:score];
	[gameOverScene.layer setResult];
	[[CCDirector sharedDirector] replaceScene:gameOverScene];
	
}


-(void)initBatch
{
	// get any bullet image from the Texture Atlas we're using
	CCSpriteFrame* bulletFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"spike.png"];
	
	// use the bullet's texture (which will be the Texture Atlas used by the game)
	batch = [CCSpriteBatchNode batchNodeWithTexture:bulletFrame.texture];
	[self addChild:batch];
	
	// Create a number of bullets up front and re-use them whenever necessary.
	for (int i = 0; i < 10; i++)
	{
		NSString* frameName = [NSString stringWithFormat:@"spike.png"];
		CCSprite* target = [CCSprite spriteWithSpriteFrameName:frameName];
		target.visible = NO;
		if (i%2) {
			target.flipY=true;
		}else {
			target.flipY=false;
		}

		
		[batch addChild:target];
	}
}


-(CCSprite *)getSpike:(bool)isFlip
{
	CCSprite * spike=nil;
	CCARRAY_FOREACH([batch children], spike)
	{
		if (!spike.visible && spike.flipY==isFlip)
		{
			break;
		}
	}
	
	return spike;
}


-(void)addTarget 
{
	int isTop=[RandomNumber createRandomsizeValueInt:0 toInt:1];
	
	//CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
	//[frameCache addSpriteFramesWithFile:@"gameEngineSpriteSheetDefault.plist"];
	
	//NSString* frameName = [NSString stringWithFormat:@"spike.png"];
	//CCSprite* target = [CCSprite spriteWithSpriteFrameName:frameName];
	CCSprite* target =[self getSpike:(bool)!isTop];
	target.visible=true;
	//CCSprite *target = [CCSprite spriteWithFile:@"bird_perky_preview.png" ]; //bird_perky_preview.png  spike.png
	
	// Determine where to spawn the target along the Y axis
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	
	int minX = 0+target.contentSize.width/2;
	int maxX = winSize.width/4+target.contentSize.width/2;
	int rangeX = maxX - minX;
	int actualX = (arc4random() % rangeX) + minX;
	

	
	int actualY;
	
	float actualScal=[RandomNumber createRandomsizeValueFloat:0.3 toFloat:0.7];
	
	
	if (isTop) {
		target.anchorPoint=ccp(0.0,1.0);
		actualY= winSize.height;
		target.tag=SPIKE_TAG_TOP;
		//target.flipY=true;
	}else {
		target.anchorPoint=ccp(0.0,0.0);
		//target.flipY=true;
		actualY= 0;
		target.tag=SPIKE_TAG_BOTTOM;
	}

	
	// Create the target slightly off-screen along the right edge,
	// and along a random position along the Y axis as calculated above
	target.position = ccp(winSize.width + actualX, actualY);
	target.scaleY=actualScal;
	//target.position = ccp(winSize.width/2, winSize.height/2);  //test
	//[self addChild:target];
	
	
	
	// Determine speed of the target
	int minDuration = 2.0;
	int maxDuration = 4.0;
	int rangeDuration = maxDuration - minDuration;
	//int actualDuration = (arc4random() % rangeDuration) + minDuration;
	float speed=winSize.width/4.0;
	float actualDuration = (winSize.width + actualX-(-target.contentSize.width/2))/speed;
	
	// Create the actions
	id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width/2, actualY)];
	id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
	[target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
	
	// Add to targets array
	//target.tag = 1;
	[_targets addObject:target];
	
	
}


-(void)spriteMoveFinished:(id)sender
{
	
	//[self removeChild:sender cleanup:YES];
	
	CCSprite * spr=(CCSprite *)sender;
	spr.visible=FALSE;
	
	[_targets removeObject:spr];
}


-(void)gameLogic:(ccTime)dt {
	
	[self addTarget];
	
}


-(void) addFireButton
{
	float buttonRadius = 50;
	CGSize screenSize = [[CCDirector sharedDirector] winSize];

	fireButton = [SneakyButton button];
	fireButton.isHoldable = YES;
	
	SneakyButtonSkinnedBase* skinFireButton = [SneakyButtonSkinnedBase skinnedButton];
	skinFireButton.position = CGPointMake(screenSize.width - buttonRadius * 1.5f, buttonRadius * 1.5f);
	skinFireButton.defaultSprite = [CCSprite spriteWithSpriteFrameName:@"button-default.png"];
	skinFireButton.pressSprite = [CCSprite spriteWithSpriteFrameName:@"button-pressed.png"];
	skinFireButton.button = fireButton;
	[self addChild:skinFireButton];
}

-(void) addJoystick
{
	float stickRadius = 50;

	joystick = [SneakyJoystick joystickWithRect:CGRectMake(0, 0, stickRadius, stickRadius)];
	joystick.autoCenter = YES;
	
	// Now with fewer directions
	joystick.isDPad = YES;
	joystick.numberOfDirections = 8;
	
	SneakyJoystickSkinnedBase* skinStick = [SneakyJoystickSkinnedBase skinnedJoystick];
	skinStick.position = CGPointMake(stickRadius * 1.5f, stickRadius * 1.5f);
	skinStick.backgroundSprite = [CCSprite spriteWithSpriteFrameName:@"button-disabled.png"];
	skinStick.backgroundSprite.color = ccMAGENTA;
	skinStick.thumbSprite = [CCSprite spriteWithSpriteFrameName:@"button-disabled.png"];
	skinStick.thumbSprite.scale = 0.5f;
	skinStick.joystick = joystick;
	[self addChild:skinStick];
}


-(void)update:(ccTime)delta
{
	if (bPowerPressed){
		// Moving the ship with the thumbstick.
		GameScene* game = [GameScene sharedGameScene];
		ShipEntity* ship = [game defaultShip];
		[ship changeBirdFrame];
	}
}

-(void) update2:(ccTime)delta
{
    
    
    
    mScore++;
    NSString * str=[NSString stringWithFormat:@"%d",mScore];
	[mFilghtScore setString:str];
    
	
	totalTime += delta;

	// Moving the ship with the thumbstick.
	GameScene* game = [GameScene sharedGameScene];
	ShipEntity* ship = [game defaultShip];
	
    CCLOG(@"ship(%f,%f,v=%d,w=%f,h=%f)",ship.position.x,ship.position.y
          ,ship.visible
          ,ship.contentSize.width,ship.contentSize.height); 
    
	// Continuous fire
	if (bPowerPressed)
	{
		posDelta+=DELTA_STEP;
		ship.position = CGPointMake(ship.position.x, ship.position.y + posDelta);

		//[ship runMoveByActionV:posDelta];
		
	}
	else {
		posDelta+=DELTA_DROP_STEP;  //加速下落，模拟重力作用
		ship.position = CGPointMake(ship.position.x, ship.position.y + posDelta);
		//[ship runMoveByActionV:posDelta];
		//[ship changeBirdFrame];
	}
    

    //ship.visible=true;

}





#pragma mark Touch Delegate

-(void)ccTouchesBegan:(NSSet*)touches 
			withEvent:(UIEvent*)event
{
	UITouch * touch=[touches anyObject];
	
	CGPoint location = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
	//if([background containsPoint:[background convertToNodeSpace:location]]){
	//location = [self convertToNodeSpace:location];
	//Do a fast rect check before doing a circle hit check:
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
    /*
	if(location.x < winSize.width/2 || location.x > winSize.width 
	   || location.y < 0 || location.y > winSize.height/2){
		//return NO;
		return;
	}else{
      */  
        
		bPowerPressed=true;
		posDelta=DELTA_BASE;
		
		GameScene* game = [GameScene sharedGameScene];
		ShipEntity* ship = [game defaultShip];
		//[ship birdPowerAnimation];
		[ship startBirdFrame];
		//return YES;
		return;
	//}
	
	//return NO;
	return;
}

-(void)ccTouchesMoved:(NSSet*)touches 
			withEvent:(UIEvent*)event
{
	
}

-(void)ccTouchesEnded:(NSSet*)touches 
			withEvent:(UIEvent*)event
{
    
    //return; //test  code
    
	UITouch * touch=[touches anyObject];
	CGPoint location=[touch locationInView:[touch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
	if(bPowerPressed)
	{
		bPowerPressed=FALSE;
		posDelta=DELTA_DROP_BASE;
		
		GameScene* game = [GameScene sharedGameScene];
		ShipEntity* ship = [game defaultShip];
		//[ship stopAllActions];
		[ship stopBirdFrame];
	}
	
}

- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event
{
	[self ccTouchEnded:touch withEvent:event];
}


//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
#pragma mark add Pause Pic


-(void)addPause
{
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
	// Image Item
	CCSprite * tmpSprite=[CCSprite spriteWithFile:@"button_pause@1x.png"];
	
	CCMenuItem *back = [CCMenuItemImage 
						itemFromNormalImage:@"button_pause@1x.png" 
						selectedImage:@"button_pause_lit@1x.png" 
						target:self 
						selector:@selector(pauseCallback:)];
	CCMenu *menuBack = [CCMenu menuWithItems:
						back,nil];
	[menuBack alignItemsHorizontally];
	menuBack.position=ccp(tmpSprite.contentSize.width/4,tmpSprite.contentSize.height/4); ///左下角
	[self addChild: menuBack z:5 tag:TAG_PAUSE];
	
}

-(void) pauseCallback: (id) sender
{
	///按钮点击的音效
	[GameMusicSetting playEffect:@"button.caf"];
	
	
	
	[self setAllMenuEnabled:false];
}


/*
 处理所有的按钮变灰和还原动作
 */
-(void)setAllMenuEnabled:(BOOL)enabled
{
	bool bEn=enabled;
	
	CGSize winSize=[[CCDirector sharedDirector] winSize];
	
	if (!bEn) {
		
		[GameMusicSetting pauseBackgroundMusic];  //暂停背景音乐
		
		///disable the button ,cover by a new layer
		
		CCColorLayer * layer = [(CCColorLayer*)[CCColorLayer alloc] initWithColor:ccc4(0, 0, 0, 200)];//看看这个函数的文档
		[self addChild:layer z:10 tag:TAG_COVER_LAYER];
		
		/////界面上增加恢复，重新开始，退出的按钮
		CGSize winSize=[[CCDirector sharedDirector] winSize];
		
		// Image Item  continue
		CCSprite * tmpSprite=[CCSprite spriteWithFile:@"button_ingame_continue@1x.png"];
		
		CCMenuItem * continue_button = [CCMenuItemImage 
										itemFromNormalImage:@"button_ingame_continue@1x.png" 
										selectedImage:@"button_ingame_continue_lit@1x.png" 
										target:self 
										selector:@selector(continueCallback:)];
		
		////重新开始
		CCMenuItem * retry_button = [CCMenuItemImage 
									 itemFromNormalImage:@"button_ingame_retry@1x.png" 
									 selectedImage:@"button_ingame_retry_lit@1x.png" 
									 target:self 
									 selector:@selector(retryCallback:)];
		
		///退出
		CCMenuItem * quit_button = [CCMenuItemImage 
									itemFromNormalImage:@"button_ingame_quit@1x.png" 
									selectedImage:@"button_ingame_quit_lit@1x.png" 
									target:self
									selector:@selector(quit_Callback:)];
		
		
		
		CCMenu *menuBack = [CCMenu menuWithItems:
							continue_button,retry_button,quit_button,nil];
		[menuBack alignItemsHorizontally];
		//menuBack.position=ccp(tmpSprite.contentSize.width/2,tmpSprite.contentSize.height/2); ///左下角
		continue_button.position=ccp(continue_button.position.x-tmpSprite.contentSize.width/2,
									 continue_button.position.y);
		
		quit_button.position=ccp(quit_button.position.x+tmpSprite.contentSize.width/2,
								 quit_button.position.y);
		
		[self addChild: menuBack z:10 tag:TAG_COVER_LAYER_MENU];   
		
		
		////暂停当前游戏的刷新
		[[CCDirector sharedDirector] pause];
	}
	else {
		
		[GameMusicSetting resumeBackgroundMusic];  //恢复背景音乐
		
		[[CCDirector sharedDirector] resume];
		
		/////恢复背景显示，使按钮可点
		[[self getChildByTag:TAG_COVER_LAYER] setVisible:NO];
		[self removeChildByTag:TAG_COVER_LAYER cleanup:YES];
		
		
		[[self getChildByTag:TAG_COVER_LAYER_MENU] setVisible:NO];
		[self removeChildByTag:TAG_COVER_LAYER_MENU cleanup:YES];
		
	}
	
	
	[self setIsTouchEnabled:bEn];
	
	
	CCMenu * menu=[self getChildByTag:TAG_PAUSE];
	for (CCNode * item in [menu children]) {
		[item setIsEnabled:bEn];
	}
}



-(void)continueCallback:(id)sender
{
	[GameMusicSetting playEffect:@"button.caf"];
	
	
	[self setAllMenuEnabled:true];
}

-(void)retryCallback:(id)sender
{
	[GameMusicSetting playEffect:@"button.caf"];
	
	[self resetGameData];
	
	[self setAllMenuEnabled:true];
}


-(void)resetScore
{
	mScore=0;
    NSString * str=[NSString stringWithFormat:@"%d",mScore];
	[mFilghtScore setString:str];
}


-(void)resetGameData
{
	[self resetScore];
	

	
	///清楚已经显示的拉登
	//NSMutableArray * array=[[NSMutableArray alloc] init];
	/////循环所有目标，这里就是老鼠和猫，看该锤子和那个动物发生了碰撞
	for (CCSprite * target in _targets) 
	{
		//[self removeChild:target cleanup:YES];
		target.visible=FALSE;
	}
	
	[_targets removeAllObjects];
}


-(void)quit_Callback:(id)sender
{
	/*
	 [GameMusicSetting playEffect:@"button.caf"];
	 
	 [self setAllMenuEnabled:true];
	 [self GameOverDelayTimeOut:self];
	 */
	[GameMusicSetting playEffect:@"button.caf"];
	[self setAllMenuEnabled:true];
	
	//[GameMusicSetting stopBackgroundMusic];  //stop背景音乐
	
	CCScene *scene = [CCScene node];
	
	CCLayer *layer = [Layer1 node];
	[scene addChild: layer z:0];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	
	[[CCDirector sharedDirector] replaceScene: scene];
	
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

#pragma mark game center 
-(void)gotoGameCenter:(id)sender
{
    //[director_ pushScene: [gameCenterLayer scene]]; 
    
    
    // [[CCDirector sharedDirector] pushScene:[gameCenterLayer scene]];
    
    
    //[OpenFeint launchDashboard];
    
    
    /*
     GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
     //gkHelper.delegate = self;
     //[gkHelper authenticateLocalPlayer];
     [gkHelper showLeaderboard];
     
     */
    
    
    ///push scene,pop scene
	CCScene *scene = [CCScene node];
	
	CCLayer *layer = [GameCenterLayer node];
	[scene addChild:layer z:1];
	
	//[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
	[[CCDirector sharedDirector] pushScene:scene];
}

-(void)addOpenFeintButton
{
    GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
    gkHelper.delegate = self;
    [gkHelper authenticateLocalPlayer];
    
    
	CCSprite * tmp=[CCSprite spriteWithFile:@"game_center_logo30.png"];
	
	CGSize size = [[CCDirector sharedDirector] winSize];
    
	
    
	CCMenuItemImage * help=[CCMenuItemImage itemFromNormalImage:@"game_center_logo30.png" 
												  selectedImage:@"game_center_logo30.png" 
														 target:self selector:@selector(gotoGameCenter:)];
	
    /*
     tmp.scale=36/(float)tmp.contentSize.width;
     CCMenuItemSprite * help=[CCMenuItemSprite itemFromNormalSprite:(CCNode<CCRGBAProtocol>*)tmp selectedSprite:(CCNode<CCRGBAProtocol>*)tmp 
     target:self selector:@selector(gotoGameCenter:)];
     */
	CCMenu * menu=[CCMenu menuWithItems:help,nil];
	menu.position=ccp(tmp.contentSize.width/2+3,size.height-tmp.contentSize.height/2-3);
	[self addChild:menu z:10 tag:10210];
	
}





#pragma mark submit game center data
-(void)submitGameCenter
{
    //[OFHighScoreService setHighScore:player_level forLeaderboard:@"player_level" onSuccess:OFDelegate() onFailure:OFDelegate()];
    
    
    /*
     [OFHighScoreService  setHighScore:player_level forLeaderboard:@"player_level" onSuccessInvocation:(OFInvocation*)nil onFailureInvocation:nil];
     */
    
    
    GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
    
    NSString * str=nil;
    
	int level=[GameMusicSetting getGameLevelSeeting];
	switch (level) {
		case NORMAL:
			//time=[self createRandomsizeValueFloat:1.0 toFloat:1.2];   ////range 1.0-2.0
			str=@"TopHighScore";
			break;
			
		case HARD:
			//time=(float)[self createRandomsizeValueFloat:0.8 toFloat:1.0]; ;   ////range 0.7-1.7
			str=@"HardTopHighScore";
			break;
			
			
		case EASY:   ////range 1.5-2.5
			//time=(float)[self createRandomsizeValueFloat:1.2 toFloat:1.5];
			str=@"EasyTopHighScore";
			break;
			
		default:
			break;
	}
    
    [gkHelper submitScore:mScore category:str];
    
    
    
    
}





@end
